package com.pkangu.nolattosio.database;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

import com.pkangu.nolattosio.database.Metadata.Comuni;
import com.pkangu.nolattosio.database.Metadata.Province;

public class DatabaseAdapter {
	private static final String LOG_TAG = DatabaseAdapter.class.getSimpleName();
	
	private Context context;
	private SQLiteDatabase database;
	private DatabaseHelper dbHelper;
	
	private static final String DATABASE_TABLE_REGIONI = "regioni";
	private static final String DATABASE_TABLE_PROVINCE = "province";
	private static final String DATABASE_TABLE_COMUNI = "comuni";
	
	public DatabaseAdapter(Context context) {
		this.context = context;
	}
	
	public DatabaseAdapter open() throws SQLException {
		dbHelper = new DatabaseHelper(context);
		database = dbHelper.getWritableDatabase();
		return this;
	}
	
	public void close() {
		dbHelper.close();
	}
	
	public Cursor fetchComuniByFilter(String filter) {
		Cursor mCursor = database.rawQuery("SELECT " + 
			Comuni.KEY_ID + " AS _id, " + 
			Comuni.KEY_NOME + ", " + 
			Province.KEY_NOME + " FROM " + 
			DATABASE_TABLE_COMUNI + " INNER JOIN " + 
			DATABASE_TABLE_PROVINCE + " ON " + 
			Comuni.KEY_ID_PROVINCIA + " = " + Province.KEY_ID + " WHERE " + 
			Comuni.KEY_NOME + " Like '%" + filter + "%';", new String[] {});
		return mCursor;
	}
	
	public Cursor fetchAllComuni() {
		Cursor mCursor = database.rawQuery("SELECT " + 
				Comuni.KEY_ID + " AS _id, " + 
				Comuni.KEY_NOME + ", " + 
				Province.KEY_NOME + " FROM " + 
				DATABASE_TABLE_COMUNI + " INNER JOIN " + 
				DATABASE_TABLE_PROVINCE + " ON " + 
				Comuni.KEY_ID_PROVINCIA + " = " + Province.KEY_ID + ";", new String[] {});
		return mCursor;
	}
	
	public Cursor fetchStocazzo() {
		Cursor mCursor = database.rawQuery("SELECT * FROM comuni;", new String[] {});
		return mCursor;
	}
	

}
